<template>
  <div>
    <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: 500px; overflow-y: hidden"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
    </div>

    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>

    <van-button @click="getInfo" type="primary">获取数据</van-button>

    <div class="table">
      <table>
        <tr>
          <th>标题</th>
          <th>简介</th>
          <th>内容</th>
          <th>分类</th>
          <th>操作</th>
        </tr>

        <tr v-for="(item, index) in Info" :key="index">
          <td>
            <MyTag
              :value="item.title"
              :itemId="item.id"
              @input="handleInput($event, item.id, 'title')"
            />
          </td>

          <td>
            <MyTag
              :value="item.summary"
              :itemId="item.id"
              @input="handleInput($event, item.id, 'summary')"
            />
          </td>
          <td>
            <MyTag
              :value="item.content"
              :itemId="item.id"
              @input="handleInput($event, item.id, 'content')"
            />
          </td>
          <td>
            <MyTag
              :value="item.collection"
              :itemId="item.id"
              @input="handleInput($event, item.id, 'collection')"
            />
          </td>

          <td><button @click="deleteInfo(item.id)">删除</button></td>
        </tr>
      </table>

      <van-cell-group inset>
        <van-field v-model="number" label="输入学号查询" placeholder="学号" />
      </van-cell-group>

      <!-- <van-button @click="searchInfo" type="primary">查询</van-button> -->

      <tr v-for="(item, index) in searchResult" :key="index">
        <td>{{ item.id }}</td>
        <td>{{ item.title }}</td>
        <td>{{ item.summary }}</td>
        <td>{{ item.content }}</td>
      </tr>
    </div>
    <ImageUpload></ImageUpload>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import ImageUpload from '@/views/ImageUpload.vue'
import axios from 'axios'
import MyTag from '@/views/MyTag.vue'
const username = ref('')
const password = ref('')
const number = ref('')
const searchResult = ref('')
const Info = ref('')

onMounted(() => {
  getInfo()
})

// const handleinput = (value) => {
//   console.log(value)
//   console.log('子传父')
// }

const handleInput = (newValue, id, field) => {
  const item = Info.value.find((item) => item.id === id)
  if (item) {
    // 更新 Info 数组中的相应项
    const updatedItem = { ...item, [field]: newValue }
    const index = Info.value.findIndex((i) => i.id === id)
    if (index !== -1) {
      Info.value[index] = updatedItem
    }
    console.log('更新后的数据', updatedItem)

    // 调用后台接口更新数据
    axios
      .post('http://localhost:3000/api/update', updatedItem)
      .then((res) => {
        console.log('更新成功', res)
      })
      .catch((err) => {
        console.error('更新失败', err)
      })
  }
}

//提交数据
const onSubmit = () => {
  axios
    .post('http://localhost:3000/api/add', {
      username: username.value,
      password: password.value
    })
    .then((res) => {
      console.log(res)
      getInfo()
    })
    .catch((err) => {
      if (err.response.status === 400) {
        alert('用户名已存在')
      }
      if (err.response.status === 500) {
        console.log('服务器错误')
        alert('服务器错误')
      }
    })
}

//获取数据
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
const getInfo = () => {
  axios
    .get('http://localhost:3000/api/get')
    .then((res) => {
      console.log(res)
      Info.value = res.data
      console.log(Info.value)
      userStore.setInfo(res.data)
    })
    .catch((err) => {
      console.log(err)
    })
}

//删除数据
const deleteInfo = (index) => {
  console.log('删除', index)
  axios.delete(`http://localhost:3000/api/delete/${index}`).then((res) => {
    console.log(res)
    getInfo()
  })
}

//查询数据

const searchInfo = () => {
  if (!number.value) {
    alert('请输入学号')
    return
  }
  axios
    .get(`http://localhost:3000/api/search/${number.value}`)
    .then((res) => {
      console.log(res)
      searchResult.value = res.data
      console.log(searchResult.value)
    })

    .catch((err) => {
      if (err.response.status === 404) {
        alert('用户不存在')
      }
    })
}
</script>

<!-- <script>
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default {
  components: { Editor, Toolbar },
  setup() {
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()

    // 内容 HTML
    const valueHtml = ref('<p>hello</p>')

    // 模拟 ajax 异步获取内容
    onMounted(() => {
        setTimeout(() => {
            valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
        }, 1500)
    })

    const toolbarConfig = {}
    const editorConfig = { placeholder: '请输入内容...' }

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
        const editor = editorRef.value
        if (editor == null) return
        editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }

    return {
      editorRef,
      valueHtml,
      mode: 'default', // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated
    };
  }
}
</script>    -->

<style>
table {
  width: 100%;
  border-collapse: collapse;
}
table th {
  background-color: #f2f2f2;
}
table td {
  width: 100px;
  border: 3px solid skyblue;
}
input {
  width: 100px;
  height: auto;
  border: 0;
}
</style>
